package struts2.sample07.action;

import java.util.Map;

import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import struts2.sample07.mapping.User;

import com.opensymphony.xwork2.ActionContext;

@Results({
	@Result("menu.jsp"),
	@Result(name="fail", value="login.jsp")
})
public class LoginAction {

	/** ユーザーID */
	private String userId;
	
	/** パスワード */
	private String password;
	
	/** hibernateのセッションファクトリー */
	private SessionFactory sessionFactory;

	
	@SuppressWarnings("unchecked")
	public String execute(){
		Session dbSession = sessionFactory.openSession();
		try{
			User user = (User)dbSession.get(User.class, userId);

			if(user == null)
				return "fail";

			if(password.equals(user.getPassword()) == false)
				return "fail";


			Map httpSession = ActionContext.getContext().getSession();
			httpSession.put("login.user", user);
			
			return "success";
		}finally{
			dbSession.close();
		}
	}

	
	//
	// setterとgetter
	//
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
